import Honey from '../../utils/honey';
import Event from '../../utils/event'

const app = getApp();
const honey = new Honey();
const event = new Event();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    pageNo: 1,
    pageSize: 10,
    status: '',
    orderList: [],
    couponList: [], //当前可使用兑换券数据
    couponListIdx: -1, //当前选择兑换券索引
    isLoad: true,
    paymentShow: false, //支付框显示隐藏
    discountsShow: false, //兑换券框控制显示
    amount:'',//当前付款商品原价
    maxHealth:0,//当前付款商品健康基金可使用金额
    payment: '2', //默认金额选择id
    payMoney: '', //当前付款金额
    disabled: true,//余额支付是否可用参数,
    name:'',//当前付款商品名称
    comboId:'',//当前付款商品ID
    items: [{
      name: '2',
      value: '微信支付',
      checked: 'true'
    },
    {
      name: '1',
      value: '余额支付'
    },
    ], //支付方式单选内容

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.check_code && !wx.getStorageSync('user')) {
      wx.setStorageSync('checkCode', options.check_code),
        wx.setStorageSync('pagesUrl', '/pages/mine/myPurchase'),
        wx.switchTab({
          url: '/pages/index/index'
        })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const that = this;
    const user = honey.checkLogin('/pages/mine/myPurchase', false);
    that.setData({
      user: user,
      orderList: [],
      isLoad: true,
      pageNo: 1
    })
    that.getOrderList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    const that = this;
    return {
      title: `平台烧钱啦～点击领取大红包！`,
      path: `/pages/mine/myPurchase?check_code=${that.data.user.check_code}`,
    }
  },
  getOrderList: function() {
    var that = this;
    if (that.data.isLoad) {
      that.setData({
        isLoad: false
      })
      honey.post({
        alias: 'orderList',
        data: {
          page: that.data.pageNo,
          status: that.data.status,
          page_size: that.data.pageSize
        },
        success: function(res) {
          that.setData({
            orderList: honey.mergeArray(that.data.orderList, res.data.data.list),
            isLoad: (res.data.data.list.length < that.data.pageSize ? false : true),
            pageNo: that.data.pageNo + 1
          })
        }
      })
    }
  },
  tapOrderStatus: function(e) {
    const that = this;
    const status = e.currentTarget.dataset.status;
    that.setData({
      status: status,
      pageNo: 1,
      orderList: [],
      isLoad: true
    })
    that.getOrderList();
  },

  //获取付款信息
  payOrderData: function(e) {
    const that = this;
    const order_sn = e.currentTarget.dataset.order;
    const amount = e.currentTarget.dataset.amount;
    const name = e.currentTarget.dataset.name;
    const comboId = e.currentTarget.dataset.id;
    honey.post({
      alias: 'payOrderData',
      data: {
        order_sn,
      },
      success(res) {
        let maxHealth = 0;
        if (res.data.data.max_health) {
          maxHealth = res.data.data.max_health;
        }
        
        let payMoney = (amount * 1 - maxHealth * 1).toFixed(2);
        let disabled = that.data.user.info.amount*1 >= payMoney*1 ? false : true;
        that.setData({
          maxHealth,
          paymentShow: true,
          orderId: order_sn,
          payment: '2',
          payMoney,
          amount,
          disabled,
          name,
          comboId
        })
        that.getCouponList();
        if (that.data.items.length == 3) {
          let items = that.data.items;
          items[0].checked = false,
            items[1].checked = false,
            items[2].checked = true,
            that.setData({
              items,
            })
          that.radioChange({ detail: { value: 3 } })
        }
        
      }
    })
  },

  payOrder: function() {
    const that = this;
    wx.showLoading({
      title: '支付中',
    })
    honey.post({
      alias: 'payOrder',
      data: {
        order_sn: that.data.orderId,
        health_pay: that.data.maxHealth, 
        pay_type: that.data.payment == 2 ? 'wx_pay' : that.data.payment == 1 ? 'amount_pay' : 'coupon_pay',
        coupon_id: that.data.couponListIdx == -1 ? '' : that.data.couponList[that.data.couponListIdx].id
      },
      success(res) {
        if (!res.data.data.payParam) {
          let orderId = res.data.data.order_sn;
          wx.navigateTo({
            url: '/pages/pay/paySuccess?id=' + orderId,
          })
        } else {
          var payParam = res.data.data.payParam;
          wx.requestPayment({
            timeStamp: payParam.timeStamp,
            nonceStr: payParam.nonceStr,
            package: payParam.package,
            signType: payParam.signType,
            paySign: payParam.paySign,
            success: function() {
              event.emit('refreshUserInfo', 'userInfo');
              wx.navigateTo({
                url: '/pages/pay/paySuccess?id=' + res.data.data.order_sn,
              })
            },
            fail: function(res) {
              event.emit('refreshUserInfo', 'userInfo');
              wx.showToast({
                title: '支付失败',
                image: '/res/images/icon-shibai.png'
              })

            },
            complete: function() {
              event.emit('refreshUserInfo', 'userInfo');
              wx.hideLoading();
            }
          })
        }
      },
      complete: function() {
        event.emit('refreshUserInfo', 'userInfo');
        wx.hideLoading();
      }
    })
  },

  //关闭支付框
  closeCashier: function() {
    const that = this;
    that.setData({
      paymentShow: false
    })
  },

  //取消订单
  cancelOrder: function(e) {
    const order_sn = e.currentTarget.dataset.order
    const that = this;
    wx.showModal({
      title: '提示',
      content: '确定取消订单?',
      success(res) {
        if (res.confirm) {
          honey.post({
            alias: 'cancelOrder',
            data: {
              order_sn
            },
            success: function(res) {
              that.tapOrderStatus()
              wx.showToast({
                title: '取消成功',
              })
            }
          })
        } else if (res.cancel) {

        }
      }
    })

  },

  //支付方式选择事件
  radioChange: function (e) {
    const that = this;
    that.setData({
      payment: e.detail.value
    })
    if (e.detail.value == 3) {
      that.setData({
        couponListIdx: 0
      })
    } else {
      that.setData({
        couponListIdx: -1
      })
    }
  },

  //打开兑换券选择框
  openTicket: function () {
    const that = this;
    that.setData({
      discountsShow: true,
    })
  },

  //获取当前商品可用兑换卷
  getCouponList: function () {
    const that = this;
    honey.post({
      alias: 'getCouponList',
      data: {
        goods_id: that.data.comboId,
        status: 0
      },
      success: function (res) {
        that.setData({
          couponList: res.data.data.couponList,
        })
        if (res.data.data.couponList.length > 0) {
          that.setData({
            items: [...that.data.items,
            {
              name: '3',
              value: '兑换券抵用'
            }
            ],

          })
        }
      }
    })
  },

  //选择兑换券
  selectTicket: function (e) {
    const that = this;
    let couponListIdx = e.currentTarget.dataset.idx;
    that.setData({
      couponListIdx,
      discountsShow: false
    })
  },
})